import { EChartOption } from 'echarts';

export default function () {
  const getSeriesColor = (seriesItem: EChartOption.SeriesBar | EChartOption.SeriesLine) => {
    const { itemStyle, areaStyle } = seriesItem;

    if (itemStyle) {
      if (typeof itemStyle?.color === 'string') {
        return itemStyle?.color;
      } else {
        return itemStyle?.color?.colorStops ? itemStyle?.color?.colorStops[1].color : '';
      }
    }

    if (areaStyle) {
      if (typeof areaStyle?.color === 'string') {
        return areaStyle?.color;
      } else {
        return areaStyle.color?.colorStops ? areaStyle.color?.colorStops[1].color : '';
      }
    }
  };

  const getLegendData = (option: EChartOption) => {
    const colors = option.color || [];
    return option.series
      ?.filter((item) => item.type !== 'custom')
      .map((item, realSeriesIndex) => {
        const type = item.type;
        switch (type) {
          case 'pie':
            return item.data?.map((item, pieIndex) => {
              return {
                type,
                label: item?.name,
                color: colors[pieIndex]
              };
            });
          case 'line':
            return {
              type,
              label: item?.name,
              color: colors[realSeriesIndex] || getSeriesColor(item as echarts.EChartOption.SeriesLine)
            };
          case 'bar':
            return {
              type,
              label: item?.name,
              color: getSeriesColor(item as echarts.EChartOption.SeriesBar)
            };
        }
      })
      .flat();
  };

  const hideLegend = (option: EChartOption) => {
    const chartType = option?.series?.[0]?.type;
    const realSeries = option.series?.filter((item) => item?.type !== 'custom');
    return chartType === 'pie' || realSeries?.length === 1;
  };

  return {
    hideLegend,
    getLegendData
  };
}
